class_name EnemySlots
extends Node2D


var _enemy_slots: Array[EnemySlot]


func _ready():
	_find_enemy_slots()



func _find_enemy_slots():
	var slots := get_children()
	for s in slots:
		if s is EnemySlot and s.enabled:
			_enemy_slots.push_back(s)


# 占据槽位，若没有可用的槽位返回null，否则返回已占据的槽位
func reserve_slot(enemy: BasicEnemy) -> EnemySlot:
	var available_slots := _enemy_slots.filter(
		func(slot):
			return slot.is_free()
	)
	if available_slots.size() == 0:
		return null
	available_slots.sort_custom(
		func(a, b):
			var distance_a := enemy.global_position.distance_squared_to(a.global_position)
			var distance_b := enemy.global_position.distance_squared_to(b.global_position)
			return distance_a < distance_b
	)
	var available_slot: EnemySlot = available_slots[0]
	available_slot.occupy(enemy)
	return available_slot


# 释放槽位
func free_slot(enemy: BasicEnemy):
	var target_slots := _enemy_slots.filter(
		func(slot):
			return slot.is_occupied(enemy)
	)
	if target_slots.size() == 1:
		target_slots[0].free_up()


func free_all_slots():
	for slots in _enemy_slots:
		slots.free_up()


func all_slots_disabled(disable: bool):
	for slots in _enemy_slots:
		slots.enabled = !disable
